package com.coocaa.x.service.litecontent.providers.skyview.host;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageParser;
import android.net.Uri;
import android.os.Build.VERSION;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.LiteContentProvider;
import com.coocaa.x.service.litecontent.LiteContentProvider.LiteContentProviderHost;
import com.coocaa.x.service.litecontent.LiteContentProvider.ResourceHandler;
import com.coocaa.x.service.litecontent.data.ResultPackage;
import com.coocaa.x.uipackage.dialog.UpgradeDialog;
import com.skyworth.framework.skysdk.android.SdCardChecker;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SkyViewHost_Com_Coocaa_X extends LiteContentProviderHost {
    private static SkyViewHost_Com_Coocaa_X instance = null;

    public static synchronized void create(Context context, LiteContentProvider provider) {
        if (instance == null)
            instance = new SkyViewHost_Com_Coocaa_X(context, provider);
    }

    private static final String MY_HOST = "com.coocaa.x";

    public SkyViewHost_Com_Coocaa_X(Context context, LiteContentProvider provider) {
        super(context, provider);
    }

    @Override
    public String myHost() {
        return MY_HOST;
    }

    @SuppressWarnings("unused")
    // 2.1、升级提示
    private ResourceHandler upgrade = new ResourceHandler(this, "/upgrade") {
        private static final int INSTALL_LOCATION_UNSPECIFIED = -1;
        private static final int INSTALL_LOCATION_AUTO = 0;
        private static final int INSTALL_LOCATION_INTERNAL_ONLY = 1;
        private static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;
        private static final String ACTION_SHOW = "show";
        private static final String ACTION_REFRESH = "refresh";

        private UpgradeDialog upgradeDialog = null;

        private int getApkPreferInstallLocation(String file) {
            int installlocation = 0;
            try {
                PackageParser.PackageLite pkg = null;
                if (VERSION.SDK_INT < 21) {
                    Method staticMethod = PackageParser.class.getDeclaredMethod("parsePackageLite",
                            new Class[]{String.class, int.class});
                    pkg = (PackageParser.PackageLite) staticMethod.invoke(null, new Object[]{
                            file, 0});
                } else {
                    Method staticMethod = PackageParser.class.getDeclaredMethod("parsePackageLite",
                            new Class[]{File.class, int.class});
                    pkg = (PackageParser.PackageLite) staticMethod.invoke(null, new Object[]{
                            new File(file), 0});
                }
                if (pkg != null)
                    installlocation = pkg.installLocation;
                Runtime.getRuntime().gc();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return installlocation;
        }

        private void installWithPackageInstaller(String apkfile) {
            try {
                Uri uri = Uri.fromFile(new File(apkfile));
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("SKYWORTH_HIDE_FLAG_PACKAGENAME", mContext.getPackageName());

                int preferlocation = getApkPreferInstallLocation(apkfile);
                LogUtils.d("HHHH", "preferlocation:" + preferlocation);
                switch (preferlocation) {
                    case INSTALL_LOCATION_INTERNAL_ONLY:
                        intent.putExtra("APP_INSTALL_LOCATION", 1);
                        break;
                    case INSTALL_LOCATION_PREFER_EXTERNAL:
                    case INSTALL_LOCATION_AUTO:
                    case INSTALL_LOCATION_UNSPECIFIED:
                        if (SdCardChecker.isSDCardAvaiable()) {
                            intent.putExtra("APP_INSTALL_LOCATION", 2);
                        } else {
                            intent.putExtra("APP_INSTALL_LOCATION", 0);
                        }
                        break;
                }
                mContext.startActivity(intent);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        private void installWithAutoInstaller(String apkfile) {
            try {
                Intent intent = new Intent("coocaa.intent.action.AUTOINSTALLER");
                intent.putExtra("apkfilepath", apkfile);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } catch (Exception e) {
                installWithPackageInstaller(apkfile);
            }
        }

        private synchronized void createUpgradeDialog() {
            if (upgradeDialog == null) {
                upgradeDialog = new UpgradeDialog(mContext);
                upgradeDialog.setOnUpdateEventListener(new UpgradeDialog.OnUpgradeDialogEventListener() {
                    @Override
                    public void onClickCallBack(String apkFilePath) {
                        if (apkFilePath != null && apkFilePath.length() > 0) {
                            CoocaaApplication.CoocaaVersion cv = null;
                            try {
                                cv = CoocaaApplication.getCoocaaVersion();
                                if (cv.major >= 5)
                                    installWithAutoInstaller(apkFilePath);
                                else
                                    installWithPackageInstaller(apkFilePath);
                            } catch (Exception e) {
                                installWithPackageInstaller(apkFilePath);
                            }
                        }
                    }
                });
            }
        }

        private void show() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    createUpgradeDialog();
                    upgradeDialog.show();
                }
            });
        }

        private void refresh(final String msg, final String apkfile, final String version,
                             final String uploadtime) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    createUpgradeDialog();
                    String _msg = msg;
                    if (apkfile == null || apkfile.equals(""))
                        _msg = "無升級信息";
                    _msg = Uri.decode(_msg);
                    upgradeDialog.show();
                    upgradeDialog.refreshUpdateMsg(msg, apkfile);
                }
            });
        }

        @Override
        public ResultPackage call(Uri uri) {
            ResultPackage rp = new ResultPackage();
            String action = uri.getQueryParameter("action");
            if (action.equals(ACTION_SHOW))
                show();
            else if (action.equals(ACTION_REFRESH)) {
                String apkfile = uri.getQueryParameter("apkfile");
                String msg = uri.getQueryParameter("msg");
                String version = uri.getQueryParameter("version");
                String size = uri.getQueryParameter("size");
                String uploadtime = uri.getQueryParameter("uploadtime");

                try {
                    Runtime.getRuntime().exec("chmod -R 755 " + apkfile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                refresh(msg, apkfile, version, uploadtime);
            }
            return rp;
        }
    };
}
